using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

using FreeFlow.Administration;
using FreeFlow.Administration.WinFormsControls;
using FreeFlow.WinFormsControls.HelperClasses;
using FreeFlow;

namespace FreeFlowAdministrator
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form
	{
    private System.ComponentModel.IContainer components;
    private System.Windows.Forms.Panel contentPanel;
    private System.Windows.Forms.ImageList imageList;
    private FreeFlow.WinFormsControls.HelperClasses.RealPosition realPosition;

    private Server server;
    private FreeFlowAdministrator.UpdateChecker updateChecker;
    private ContextMenuStrip contextMenuStrip;
    private ToolStripMenuItem refreshToolStripMenuItem;
    private ToolStripMenuItem clearToolStripMenuItem;
    private ToolStripMenuItem deleteToolStripMenuItem;
    private ToolStripMenuItem fileToolStripMenuItem;
    private Splitter splitter;
    private TreeView proceduresTreeView;
    private MenuStrip menuStrip;
    private ToolStripMenuItem fileToolStripMenuItem1;
    private ToolStripMenuItem loginToolStripMenuItem;
    private ToolStripMenuItem logoutToolStripMenuItem;
    private ToolStripMenuItem exitToolStripMenuItem;
    private ToolStripMenuItem helpToolStripMenuItem1;
    private ToolStripMenuItem checkForUpdateToolStripMenuItem;
    private ToolStripMenuItem provideFeedbackToolStripMenuItem;
    private ToolStripMenuItem aboutToolStripMenuItem;
    private DevExpress.LookAndFeel.DefaultLookAndFeel defaultLookAndFeel1;
    private ToolStripMenuItem helpToolStripMenuItem;

		public MainForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
        if (server != null)
        {
          server.Dispose();
        }
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
      this.components = new System.ComponentModel.Container();
      System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
      this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
      this.refreshToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.clearToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.imageList = new System.Windows.Forms.ImageList(this.components);
      this.contentPanel = new System.Windows.Forms.Panel();
      this.realPosition = new FreeFlow.WinFormsControls.HelperClasses.RealPosition(this.components);
      this.proceduresTreeView = new System.Windows.Forms.TreeView();
      this.splitter = new System.Windows.Forms.Splitter();
      this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.menuStrip = new System.Windows.Forms.MenuStrip();
      this.fileToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
      this.loginToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.logoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.helpToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
      this.checkForUpdateToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.provideFeedbackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
      this.updateChecker = new FreeFlowAdministrator.UpdateChecker(this.components);
      this.defaultLookAndFeel1 = new DevExpress.LookAndFeel.DefaultLookAndFeel(this.components);
      this.contextMenuStrip.SuspendLayout();
      this.menuStrip.SuspendLayout();
      this.SuspendLayout();
      // 
      // contextMenuStrip
      // 
      this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.refreshToolStripMenuItem,
            this.clearToolStripMenuItem,
            this.deleteToolStripMenuItem});
      this.contextMenuStrip.Name = "contextMenuStrip";
      this.contextMenuStrip.Size = new System.Drawing.Size(114, 70);
      this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip_Opening);
      // 
      // refreshToolStripMenuItem
      // 
      this.refreshToolStripMenuItem.Image = global::FreeFlowAdministrator.Properties.Resources.refresh;
      this.refreshToolStripMenuItem.Name = "refreshToolStripMenuItem";
      this.refreshToolStripMenuItem.Size = new System.Drawing.Size(113, 22);
      this.refreshToolStripMenuItem.Text = "Refresh";
      this.refreshToolStripMenuItem.Click += new System.EventHandler(this.refresh_Click);
      // 
      // clearToolStripMenuItem
      // 
      this.clearToolStripMenuItem.Name = "clearToolStripMenuItem";
      this.clearToolStripMenuItem.Size = new System.Drawing.Size(113, 22);
      this.clearToolStripMenuItem.Text = "Clear";
      this.clearToolStripMenuItem.Click += new System.EventHandler(this.clearPopup_Click);
      // 
      // deleteToolStripMenuItem
      // 
      this.deleteToolStripMenuItem.Image = global::FreeFlowAdministrator.Properties.Resources.delete;
      this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
      this.deleteToolStripMenuItem.Size = new System.Drawing.Size(113, 22);
      this.deleteToolStripMenuItem.Text = "Delete";
      this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteMenuItem_Click);
      // 
      // imageList
      // 
      this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
      this.imageList.TransparentColor = System.Drawing.Color.Transparent;
      this.imageList.Images.SetKeyName(0, "");
      this.imageList.Images.SetKeyName(1, "");
      this.imageList.Images.SetKeyName(2, "");
      this.imageList.Images.SetKeyName(3, "");
      this.imageList.Images.SetKeyName(4, "");
      this.imageList.Images.SetKeyName(5, "");
      this.imageList.Images.SetKeyName(6, "");
      this.imageList.Images.SetKeyName(7, "");
      this.imageList.Images.SetKeyName(8, "");
      this.imageList.Images.SetKeyName(9, "");
      this.imageList.Images.SetKeyName(10, "");
      this.imageList.Images.SetKeyName(11, "");
      this.imageList.Images.SetKeyName(12, "");
      this.imageList.Images.SetKeyName(13, "");
      this.imageList.Images.SetKeyName(14, "");
      this.imageList.Images.SetKeyName(15, "");
      this.imageList.Images.SetKeyName(16, "");
      this.imageList.Images.SetKeyName(17, "");
      this.imageList.Images.SetKeyName(18, "");
      this.imageList.Images.SetKeyName(19, "");
      this.imageList.Images.SetKeyName(20, "");
      this.imageList.Images.SetKeyName(21, "");
      this.imageList.Images.SetKeyName(22, "");
      this.imageList.Images.SetKeyName(23, "");
      this.imageList.Images.SetKeyName(24, "");
      this.imageList.Images.SetKeyName(25, "");
      this.imageList.Images.SetKeyName(26, "");
      this.imageList.Images.SetKeyName(27, "");
      this.imageList.Images.SetKeyName(28, "");
      this.imageList.Images.SetKeyName(29, "");
      this.imageList.Images.SetKeyName(30, "");
      this.imageList.Images.SetKeyName(31, "");
      this.imageList.Images.SetKeyName(32, "");
      this.imageList.Images.SetKeyName(33, "");
      this.imageList.Images.SetKeyName(34, "");
      this.imageList.Images.SetKeyName(35, "");
      this.imageList.Images.SetKeyName(36, "");
      this.imageList.Images.SetKeyName(37, "information.png");
      this.imageList.Images.SetKeyName(38, "warning.png");
      this.imageList.Images.SetKeyName(39, "moneybag_dollar.png");
      this.imageList.Images.SetKeyName(40, "find.png");
      // 
      // contentPanel
      // 
      this.contentPanel.Dock = System.Windows.Forms.DockStyle.Fill;
      this.contentPanel.Location = new System.Drawing.Point(124, 24);
      this.contentPanel.Name = "contentPanel";
      this.contentPanel.Size = new System.Drawing.Size(660, 540);
      this.contentPanel.TabIndex = 2;
      // 
      // realPosition
      // 
      this.realPosition.Parent = this;
      this.realPosition.RegistryPath = "Software\\FreeFlow\\Administrator\\MainForm";
      // 
      // proceduresTreeView
      // 
      this.proceduresTreeView.ContextMenuStrip = this.contextMenuStrip;
      this.proceduresTreeView.Dock = System.Windows.Forms.DockStyle.Left;
      this.proceduresTreeView.HideSelection = false;
      this.proceduresTreeView.ImageIndex = 0;
      this.proceduresTreeView.ImageList = this.imageList;
      this.proceduresTreeView.Location = new System.Drawing.Point(0, 24);
      this.proceduresTreeView.Name = "proceduresTreeView";
      this.realPosition.SetRestoreLocation(this.proceduresTreeView, true);
      this.proceduresTreeView.SelectedImageIndex = 0;
      this.proceduresTreeView.Size = new System.Drawing.Size(121, 540);
      this.proceduresTreeView.TabIndex = 4;
      this.proceduresTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.proceduresTreeView_AfterSelect);
      // 
      // splitter
      // 
      this.splitter.Location = new System.Drawing.Point(121, 24);
      this.splitter.Name = "splitter";
      this.realPosition.SetRestoreLocation(this.splitter, true);
      this.splitter.Size = new System.Drawing.Size(3, 540);
      this.splitter.TabIndex = 5;
      this.splitter.TabStop = false;
      // 
      // fileToolStripMenuItem
      // 
      this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
      this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
      this.fileToolStripMenuItem.Text = "File";
      // 
      // helpToolStripMenuItem
      // 
      this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
      this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20);
      this.helpToolStripMenuItem.Text = "Help";
      // 
      // menuStrip
      // 
      this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem1,
            this.helpToolStripMenuItem1});
      this.menuStrip.Location = new System.Drawing.Point(0, 0);
      this.menuStrip.Name = "menuStrip";
      this.menuStrip.Size = new System.Drawing.Size(784, 24);
      this.menuStrip.TabIndex = 3;
      this.menuStrip.Text = "menuStrip1";
      // 
      // fileToolStripMenuItem1
      // 
      this.fileToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.loginToolStripMenuItem,
            this.logoutToolStripMenuItem,
            this.exitToolStripMenuItem});
      this.fileToolStripMenuItem1.Name = "fileToolStripMenuItem1";
      this.fileToolStripMenuItem1.Size = new System.Drawing.Size(37, 20);
      this.fileToolStripMenuItem1.Text = "File";
      // 
      // loginToolStripMenuItem
      // 
      this.loginToolStripMenuItem.Image = global::FreeFlowAdministrator.Properties.Resources.data_into;
      this.loginToolStripMenuItem.Name = "loginToolStripMenuItem";
      this.loginToolStripMenuItem.Size = new System.Drawing.Size(113, 22);
      this.loginToolStripMenuItem.Text = "Login...";
      this.loginToolStripMenuItem.Click += new System.EventHandler(this.login_Click);
      // 
      // logoutToolStripMenuItem
      // 
      this.logoutToolStripMenuItem.Image = global::FreeFlowAdministrator.Properties.Resources.data_previous;
      this.logoutToolStripMenuItem.Name = "logoutToolStripMenuItem";
      this.logoutToolStripMenuItem.Size = new System.Drawing.Size(113, 22);
      this.logoutToolStripMenuItem.Text = "Logout";
      this.logoutToolStripMenuItem.Click += new System.EventHandler(this.logoutMenuItem_Click);
      // 
      // exitToolStripMenuItem
      // 
      this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
      this.exitToolStripMenuItem.Size = new System.Drawing.Size(113, 22);
      this.exitToolStripMenuItem.Text = "Exit";
      this.exitToolStripMenuItem.Click += new System.EventHandler(this.exit_Click);
      // 
      // helpToolStripMenuItem1
      // 
      this.helpToolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.checkForUpdateToolStripMenuItem,
            this.provideFeedbackToolStripMenuItem,
            this.aboutToolStripMenuItem});
      this.helpToolStripMenuItem1.Name = "helpToolStripMenuItem1";
      this.helpToolStripMenuItem1.Size = new System.Drawing.Size(44, 20);
      this.helpToolStripMenuItem1.Text = "Help";
      // 
      // checkForUpdateToolStripMenuItem
      // 
      this.checkForUpdateToolStripMenuItem.Name = "checkForUpdateToolStripMenuItem";
      this.checkForUpdateToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
      this.checkForUpdateToolStripMenuItem.Text = "Check For Update...";
      this.checkForUpdateToolStripMenuItem.Click += new System.EventHandler(this.checkForUpdateMenuItem_Click);
      // 
      // provideFeedbackToolStripMenuItem
      // 
      this.provideFeedbackToolStripMenuItem.Name = "provideFeedbackToolStripMenuItem";
      this.provideFeedbackToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
      this.provideFeedbackToolStripMenuItem.Text = "Provide Feedback...";
      this.provideFeedbackToolStripMenuItem.Click += new System.EventHandler(this.feedbackMenuItem_Click);
      // 
      // aboutToolStripMenuItem
      // 
      this.aboutToolStripMenuItem.Image = global::FreeFlowAdministrator.Properties.Resources.about;
      this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
      this.aboutToolStripMenuItem.Size = new System.Drawing.Size(177, 22);
      this.aboutToolStripMenuItem.Text = "About";
      this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutMenuItem_Click);
      // 
      // updateChecker
      // 
      this.updateChecker.Url = "http://www.freeflownet.com/version.txt";
      // 
      // defaultLookAndFeel1
      // 
      this.defaultLookAndFeel1.LookAndFeel.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003;
      this.defaultLookAndFeel1.LookAndFeel.UseWindowsXPTheme = true;
      // 
      // MainForm
      // 
      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(784, 564);
      this.Controls.Add(this.contentPanel);
      this.Controls.Add(this.splitter);
      this.Controls.Add(this.proceduresTreeView);
      this.Controls.Add(this.menuStrip);
      this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
      this.MinimumSize = new System.Drawing.Size(800, 600);
      this.Name = "MainForm";
      this.realPosition.SetRestoreLocation(this, true);
      this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
      this.Text = "FreeFlow Administrator";
      this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
      this.Load += new System.EventHandler(this.MainForm_Load);
      this.contextMenuStrip.ResumeLayout(false);
      this.menuStrip.ResumeLayout(false);
      this.menuStrip.PerformLayout();
      this.ResumeLayout(false);
      this.PerformLayout();

    }
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
      ExceptionLogger logger = new ExceptionLogger();
      logger.LogType = ExceptionLogType.WebSite;
      logger.Url = "http://www.FreeFlowNet.com/SubmitBug.aspx";
      logger.QueryString = "msg={0}";

      Application.EnableVisualStyles(); 
      Application.DoEvents();

			Application.Run(new MainForm());
		}

    private void proceduresTreeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
    {
      // show children for selected item
      LoadAdaptor(e.Node);
    }

    private void LoadAdaptor(TreeNode node)
    {
      if (node.Tag is Adaptor)
      {
        Adaptor adaptor = (Adaptor)node.Tag;
        using (new CursorHandler())
        {
          node.Text = adaptor.Text + " (loading...)";
          try
          {
            Application.DoEvents();
            proceduresTreeView.BeginUpdate();
            try
            {
              Control renderer = adaptor.GetRenderer();
              if (renderer != null)
              {
                // clean up old controls
                while (contentPanel.Controls.Count > 0)
                {
                  Control thisControl = contentPanel.Controls[0];
                  if (thisControl is AdminUserControl)
                  {
                    if (((AdminUserControl)thisControl).CanDispose)
                      thisControl.Dispose();
                  }
                  else
                    thisControl.Dispose();
                  contentPanel.Controls.Remove(thisControl);
                }

                contentPanel.Controls.Add(renderer);
                renderer.Dock = DockStyle.Fill;
              }
              if (node.Nodes.Count == 0)
              {
                adaptor.AddChildren(node);
                node.Expand();
              }
            }
            finally
            {
              proceduresTreeView.EndUpdate();
            }
          }
          finally
          {
            node.Text = adaptor.Text;
          }
        }
      }
    }

    private void exit_Click(object sender, System.EventArgs e)
    {
      Close();
    }

    private void login_Click(object sender, System.EventArgs e)
    {
      Login();
    }

    private void logoutMenuItem_Click(object sender, System.EventArgs e)
    {
      Text = "FreeFlow Administrator";
      server = null;
      proceduresTreeView.BeginUpdate();
      try
      {
        proceduresTreeView.Nodes.Clear();
        CreateRegistrySettings();
        CreateOptions();
      }
      finally
      {
        proceduresTreeView.EndUpdate();
      }
      proceduresTreeView.SelectedNode = proceduresTreeView.Nodes[0];
    }

    private void CreateRegistrySettings()
    {
      TreeNode registrySettingsNode = TreeNodeFactory.CreateTreeNode(new RegistrySettingsAdaptor());
      proceduresTreeView.Nodes.Add(registrySettingsNode);
    }

    private void CreateOptions()
    {
      TreeNode optionsNode = TreeNodeFactory.CreateTreeNode(new OptionsAdaptor(server));
      proceduresTreeView.Nodes.Add(optionsNode);

      TreeNode donateNode = TreeNodeFactory.CreateTreeNode(new DonateAdaptor());
      proceduresTreeView.Nodes.Add(donateNode);
    }

    private TreeNode sqlWindowNode;
    private SqlWindowAdaptor sqlWindowAdaptor;
    private void Login()
    {
      server = new Server();

      if (LoginForm.ShowLoginDialog(server) == DialogResult.OK)
      {
        using (new CursorHandler())
        {
          server.QueryTimeout = OptionsControl.QueryTimeout();
          Text = server.Database + "@" + server.Datasource + " - FreeFlow Administrator";

          proceduresTreeView.BeginUpdate();
          try
          {
            proceduresTreeView.Nodes.Clear();

            // database settings
            TreeNode serverSettingsNode = TreeNodeFactory.CreateTreeNode(new ServerSettingsAdaptor(server));
            proceduresTreeView.Nodes.Add(serverSettingsNode);

            // registry settings
            CreateRegistrySettings();

            // authentication scripts
            TreeNode authenticationScriptsNode = TreeNodeFactory.CreateTreeNode(new AuthenticationScriptsAdaptor(server.AuthenticationScripts));
            proceduresTreeView.Nodes.Add(authenticationScriptsNode);

            // procedures
            TreeNode proceduresNode = TreeNodeFactory.CreateTreeNode(new ProceduresAdaptor(server.Procedures));
            proceduresTreeView.Nodes.Add(proceduresNode);
          
            // libraries
            TreeNode libsNode = TreeNodeFactory.CreateTreeNode(new LibrariesAdaptor(server.Libraries));
            proceduresTreeView.Nodes.Add(libsNode);

            // maps
            TreeNode mapsNode = TreeNodeFactory.CreateTreeNode(new MapsAdaptor(server.Maps));
            proceduresTreeView.Nodes.Add(mapsNode);

            // workflows
            if (server.SchemaVersion >= SchemaVersion.Version76)
            {
              TreeNode workflowsNode = TreeNodeFactory.CreateTreeNode(new WorkflowsAdaptor(server.Workflows));
              proceduresTreeView.Nodes.Add(workflowsNode);

              TreeNode workflowInstancesNode = TreeNodeFactory.CreateTreeNode(
                new WorkflowInstancesAdaptor(server.WorkflowInstances));
              proceduresTreeView.Nodes.Add(workflowInstancesNode);
            }

            // users
            TreeNode usersNode = TreeNodeFactory.CreateTreeNode(new UsersAdaptor(server.Users));
            proceduresTreeView.Nodes.Add(usersNode);

            // roles
            TreeNode rolesNode = TreeNodeFactory.CreateTreeNode(new RolesAdaptor(server.Roles));
            proceduresTreeView.Nodes.Add(rolesNode);

            // designer log
            TreeNode designerLogNode = TreeNodeFactory.CreateTreeNode(new DesignerLogAdaptor(server.DesignerLog));
            proceduresTreeView.Nodes.Add(designerLogNode);

            // event log
            CreateEventLog();

            // authentication failures
            TreeNode AuthenticationFailuresNode = TreeNodeFactory.CreateTreeNode(new AuthenticationFailuresAdaptor(server.AuthenticationFailures));
            proceduresTreeView.Nodes.Add(AuthenticationFailuresNode);

            // sessions
            TreeNode sessionsNode = TreeNodeFactory.CreateTreeNode(new SessionsAdaptor(server.Sessions));
            proceduresTreeView.Nodes.Add(sessionsNode);

            // reports
            TreeNode reportsNode = TreeNodeFactory.CreateTreeNode(new ReportsAdaptor(server.Reports));
            proceduresTreeView.Nodes.Add(reportsNode);

            // find folder
            TreeNode findFolderNode = TreeNodeFactory.CreateTreeNode(new FindFolderAdaptor(server));
            proceduresTreeView.Nodes.Add(findFolderNode);

            // search
            if (server.DatabaseType == DatabaseType.SqlServer)
            {
              TreeNode searchNode = TreeNodeFactory.CreateTreeNode(new SearchAdaptor(server));
              proceduresTreeView.Nodes.Add(searchNode);
            }

            // tables
            TreeNode tablesNode = TreeNodeFactory.CreateTreeNode(new TablesAdaptor(server.Tables));
            proceduresTreeView.Nodes.Add(tablesNode);

            // SQL window
            sqlWindowAdaptor = new SqlWindowAdaptor(server);
            sqlWindowNode = TreeNodeFactory.CreateTreeNode(sqlWindowAdaptor);
            proceduresTreeView.Nodes.Add(sqlWindowNode);

            // SQL log
            SqlLogAdaptor logAdaptor = new SqlLogAdaptor(server);
            logAdaptor.ExecuteSelected += new EventHandler<SqlExecutingEventArgs>(logAdaptor_ExecuteSelected);
            TreeNode sqlLogNode = TreeNodeFactory.CreateTreeNode(logAdaptor);
            proceduresTreeView.Nodes.Add(sqlLogNode);

            CreateOptions();

            proceduresTreeView.SelectedNode = proceduresTreeView.Nodes[0];
          }
          finally
          {
            proceduresTreeView.EndUpdate();
          }
        }
      }
    }

    private void MainForm_Load(object sender, System.EventArgs e)
    {
      CreateRegistrySettings();
      CreateEventLog();
      CreateOptions();
      Login();
    }

    private void CreateEventLog()
    {
      FreeFlow.Administration.EventLog log = new FreeFlow.Administration.EventLog();
      TreeNode eventLogNode = TreeNodeFactory.CreateTreeNode(new EventLogAdaptor(log));
      proceduresTreeView.Nodes.Add(eventLogNode);
    }

    private void RefreshAdaptor(TreeNode treeNode)
    {
      if (treeNode.Tag is IRefreshable)
      {
        proceduresTreeView.BeginUpdate();
        try
        {
          treeNode.Nodes.Clear();
          IRefreshable refreshable = (IRefreshable)treeNode.Tag;
          refreshable.Refresh();
          LoadAdaptor(treeNode);
        }
        catch (ItemDeletedException e)
        {
          MessageBox.Show(e.Message);
          ((AdaptorTreeNode)treeNode).RemoveAndRefreshParent();
        }
        finally
        {
          proceduresTreeView.EndUpdate();
        }
      }
    }

    private void refresh_Click(object sender, System.EventArgs e)
    {
      if (proceduresTreeView.SelectedNode != null)
      {
        RefreshAdaptor(proceduresTreeView.SelectedNode);
      }
    }

    private void clearPopup_Click(object sender, System.EventArgs e)
    {
      TreeNode node = proceduresTreeView.SelectedNode;
      if (node != null)
      {
        if (node.Tag is IClearable)
        {
          if (MessageBox.Show("Clear \'" + node.Text + "\'?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
          {
            using (new CursorHandler())
            {
              proceduresTreeView.BeginUpdate();
              try
              {
                node.Nodes.Clear();
                IClearable clearable = (IClearable)node.Tag;
                clearable.Clear();
                LoadAdaptor(node);
              }
              finally
              {
                proceduresTreeView.EndUpdate();
              }
            }
          }
        }
      }
    }

    private void deleteMenuItem_Click(object sender, System.EventArgs e)
    {
      TreeNode node = proceduresTreeView.SelectedNode;
      if (MessageBox.Show("Delete \'" + node.Text + "\'?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
      {
        using (new CursorHandler())
        {
          (node.Tag as IDeletable).Delete();
          ((AdaptorTreeNode)node).RemoveAndRefreshParent();
        }
      }
    }

    private void aboutMenuItem_Click(object sender, System.EventArgs e)
    {
      using (AboutForm aboutForm = new AboutForm())
      {
        aboutForm.ShowDialog();
      }
    }

    private void logAdaptor_ExecuteSelected(object sender, SqlExecutingEventArgs e)
    {
      proceduresTreeView.SelectedNode = sqlWindowNode;
      sqlWindowAdaptor.ExecuteSql(e.Sql);
    }

    private void checkForUpdateMenuItem_Click(object sender, System.EventArgs e)
    {
      updateChecker.CheckLatestVersion();
    }

    private void feedbackMenuItem_Click(object sender, System.EventArgs e)
    {
      Process.Start("http://www.freeflownet.com/suggestions.aspx");
    }

    private void contextMenuStrip_Opening(object sender, CancelEventArgs e)
    {
      refreshToolStripMenuItem.Enabled = ((proceduresTreeView.SelectedNode != null) &&
        (proceduresTreeView.SelectedNode.Tag is IRefreshable));
      clearToolStripMenuItem.Enabled = ((proceduresTreeView.SelectedNode != null) &&
        (proceduresTreeView.SelectedNode.Tag is IClearable));
      deleteToolStripMenuItem.Enabled = ((proceduresTreeView.SelectedNode != null) &&
        (proceduresTreeView.SelectedNode.Tag is IDeletable));
    }
  }
}
